package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        List<CourseCategoryTreeDto> courseCategoryTreeDtoList = courseCategoryMapper.selectTreeNodes(id);
        //TODO 组装树
        Map<String, CourseCategoryTreeDto> tempMap =
                courseCategoryTreeDtoList.stream()
                        .filter(item -> !id.equals(item.getId()))
                        .collect(Collectors.toMap(CourseCategory::getId, value -> value, (key1, key2) -> key2));
        List<CourseCategoryTreeDto> returnTreeNodes = new ArrayList<>();
        // 排除根节点
        courseCategoryTreeDtoList.stream().filter(item -> !id.equals(item.getId())).forEach(
                item -> {
                    //找到根节点下的一级节点
                    if (id.equals(item.getParentid())) {
                        returnTreeNodes.add(item);
                    }
                    //找到该节点的父节点
                    CourseCategoryTreeDto parent = tempMap.get(item.getParentid());
                    //根节点没有父节点
                    if (parent != null) {
                        //如果父节点没有子节点，则添加
                        if (parent.getChildrenTreeNodes() == null) {
                            parent.setChildrenTreeNodes(new ArrayList<>());
                        }
                        parent.getChildrenTreeNodes().add(item);
                    }
                }
        );
        return returnTreeNodes;
    }
}
